package com.zy.community.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zy.community.system.domain.SysArea;
import com.zy.community.system.dto.AreaDto;
import com.zy.community.system.mapper.SysAreaMapper;
import com.zy.community.system.service.ISysAreaService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysAreaServiceImpl implements ISysAreaService {
    @Resource
    private SysAreaMapper sysAreaMapper;

    @Override
    public List<AreaDto> findRootArea() {
        List<SysArea> allAreaRows = sysAreaMapper.findAll();
        return allAreaRows.stream().filter(area -> area.getParentCode().equals(0))
                .map(area -> {
                    AreaDto areaDto = new AreaDto();
                    areaDto.setName(area.getName());
                    areaDto.setCode(area.getCode());
                    areaDto.setChildren(getChildrenArea(areaDto, allAreaRows));
                    return areaDto;
                }).collect(Collectors.toList());
    }

    /**
     * 递归设置区域信息
     *
     * @param dto   上级区域信息
     * @param areas 所有区域信息
     * @return 子区域信息
     */
    private List<AreaDto> getChildrenArea(AreaDto dto, List<SysArea> areas) {
        List<SysArea> collect = areas.stream().filter(sysArea -> sysArea.getParentCode().equals(dto.getCode())).collect(Collectors.toList());
        if (collect != null && collect.size() > 0) {
            return collect.stream().map(area -> {
                AreaDto areaDto = new AreaDto();
                areaDto.setCode(area.getCode());
                areaDto.setName(area.getName());
                areaDto.setChildren(getChildrenArea(areaDto, areas));
                return areaDto;
            }).collect(Collectors.toList());
        }
        return null;
    }
}
